﻿namespace Blaze.Framework
{
    using UnityEngine;
    using UnityEngine.Events;

    /// <summary>
    /// 用于监听碰撞相关事件。
    /// </summary>
    public class CollisionEventListener : MonoBehaviour
    {
        [System.Serializable]
        public class TriggerEvent : UnityEvent<Collider>
        {
        }

        public TriggerEvent TriggerEnter
        {
            get
            {
                if (mTriggerEnter == null)
                    mTriggerEnter = new TriggerEvent();
                return mTriggerEnter;
            }
        }

        public TriggerEvent TriggerExit
        {
            get
            {
                if (mTriggerExit == null)
                    mTriggerExit = new TriggerEvent();
                return mTriggerExit;
            }
        }

        public TriggerEvent TriggerStay
        {
            get
            {
                if (mTriggerStaty == null)
                    mTriggerStaty = new TriggerEvent();
                return mTriggerStaty;
            }
        }

        /// <summary>
        /// 获取/创建指定对象上的碰撞事件监听器。
        /// </summary>
        public static CollisionEventListener Get(GameObject target)
        {
            return target.GetOrAddComponent<CollisionEventListener>();
        }

        private void OnDestroy()
        {
            TriggerEnter.RemoveAllListeners();
            TriggerExit.RemoveAllListeners();
            TriggerStay.RemoveAllListeners();
        }

        private void OnTriggerEnter(Collider other)
        {
            if (mTriggerEnter != null)
                mTriggerEnter.Invoke(other);
        }

        private void OnTriggerExit(Collider other)
        {
            if (mTriggerExit != null)
                mTriggerExit.Invoke(other);
        }

        private void OnTriggerStay(Collider other)
        {
            if (mTriggerStaty != null)
                mTriggerStaty.Invoke(other);
        }

        private TriggerEvent mTriggerEnter;

        private TriggerEvent mTriggerExit;
        private TriggerEvent mTriggerStaty;
    }
}